/**
 * 机器管理路由
 *
 * Created by snowingsea on 2020/02/24.
 */
const middleware = require('./../middleware');
const machine = require('./../../models/machine');
const PhoenixError = require('./../../models/phoenix-error');

/**
 * 获取机器码信息
 * @param req
 * @param res
 * @param next
 */
function getMachineCode(req, res, next) {
  let shortCode = false;
  if (req.query.short && Number(req.query.short)) {
    shortCode = true;
  }
  machine.getCode(shortCode)
    .then((machineCode) => {
      // 替换wukong相关内容
      machineCode = machineCode.replace(/wukong[^"]*/g, (rs) => '*'.repeat(rs.length));
      res.json({ machineCode });
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * Export model definition object.
 */
module.exports = (app, prefix) => {
  const machineCodeURL = `${prefix}/machine/code.json`;

  // 获取机器码
  app.get(machineCodeURL, middleware.user.requireTokenUnexpired);
  app.get(machineCodeURL, middleware.user.requireAvailable);
  app.get(machineCodeURL, middleware.user.requireAdministrator);
  app.get(machineCodeURL, getMachineCode);
};
